package tech.aistar.corejava.day13;

import java.io.*;

/**
 * @Author: lya
 * @Description: 本类的作用描述:字节输入流和字节输出流
 * @CreateDate: 2019/8/2
 * @Version: 1.0
 */
public class IODemo01 {
    public static void main(String[] args) {
        copy("d:/家居.png","d:/家居_副本.png");
    }

    private static void copy(String src,String target) {
        //1. 选流 FileInputStream和FileOutputStream
        InputStream in = null;
        OutputStream out = null;

        //2.代码体现出源头和目标
        //输出 - 从磁盘到JVM内存
        //输出 - 从JVM内存写入到磁盘
        try {
            in = new FileInputStream(src);
            out = new FileOutputStream(target);

            //int read();//一个字节一个字节的进行读取
            while(true){
                int b = in.read();
                //退出 - 当没有字节可以被读入的时候,read方法返回-1
                if(b == -1){
                    break;
                }
                //System.out.println(b);

                //一个字节一个字节写出去
                out.write(b);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            //关闭流
            //适合释放资源
            //IO流是一个昂贵的资源,用完需要及时关闭
            if(null != in){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(null != out){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
